<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Admin extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper(array('form', 'url', 'assets', 'html', 'file'));
        $this->load->library('form_validation');
        $this->load->library('security');
        $this->load->library('lib_admin');
        $this->load->library('lib_user');
        $this->load->library('lib_party');
        $this->load->model('party_model');
    }

    function index() {
        if ($message = $this->session->flashdata('message')) {
            $this->load->view('admin/general_message', array('message' => $message));
        } else {
            redirect('/admin/login/');
        }
    }

    /**
     * Login user on the site
     *
     * @return void
     */
    function login() {
        if ($this->lib_admin->is_logged_in()) {          // logged in
            redirect('admin/success');
        } else {

            $this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_checkPassword');

            if ($this->form_validation->run()) {         // validation ok
                redirect('admin/success');
            }
        }

        $this->load->view('admin/admin_login_form');
    }

    /**
     * Logout user
     *
     * @return void
     */
    function logout() {
        $this->lib_admin->logout();

        $this->_show_message($this->lang->line('auth_message_logged_out'));
    }

    function checkPassword($str) {

        if ($this->lib_admin->login($str)) {
            return true;
        }

        $this->form_validation->set_message('checkPassword', 'Mauvais mot de passe');
        return false;
    }

    function success() {
        $this->_check_auth();

        $tpl['main'] = $this->load->view('admin/success', '', true);

        $this->load->view('admin/template', $tpl);
    }

    function listUsers() {
        $this->_check_auth();

//load library
        $this->load->library('table');

//make html table for users' list
        $this->table->set_heading('id', 'pseudo', 'prénom', 'nom', 'modifier', 'supprimer');
        $this->table->set_caption('<h3>Utilisateurs</h3>');
        $datas['list'] = $this->table->generate($this->lib_user->get_list_users_for_table());

//set up view
        $tpl['main'] = $this->load->view('admin/list_users', $datas, true);
        $tpl['title'] = 'Liste des utilisateurs';
        $tpl['js'][] = js_url('delete_user');
        $this->load->view('admin/template', $tpl);
    }

    function updateUser() {
//Check login
        $this->_check_auth();

        $currentUserId = (int) $this->uri->segment(3);

        $this->form_validation->set_rules('surname', 'Nom', 'trim|required');
        $this->form_validation->set_rules('firstname', 'Prénom', 'trim|required');
        $this->form_validation->set_rules('city', 'Ville', 'trim|required');
        $this->form_validation->set_rules('phone', 'Téléphone', 'trim|required');
        $this->form_validation->set_rules('dob', 'Année de naissance');

        $data['errors'] = array();

        if ($this->form_validation->run()) {        // validation ok
            if ($this->lib_user->modify_account($currentUserId,
                            $this->input->post('surname'),
                            $this->input->post('firstname'),
                            $this->input->post('city'),
                            $this->input->post('phone'),
                            $this->input->post('dob'))) { // success
                $this->session->set_flashdata('message', 'Modifications enregistrées !');
                redirect('admin/listUsers');
            } else {                // fail
                $this->session->set_flashdata('message', 'Modifications interrompues, réessayez ! <br /> si le problème subsiste contactez l\'administrateur');
                redirect('admin/listUsers');
            }
        }
//get user datas
        $datas['user_infos'] = (array) $this->lib_user->get_user_by_id($currentUserId);
        $this->load->view('auth/update_user', $datas);
    }

    function deleteUser() {
//Check login
        $this->_check_auth();

        $currentUserId = (int) $this->uri->segment(3);
        $this->user_model->delete_user($currentUserId);

        $this->session->set_flashdata('message', 'Utilisateur ' . $currentUserId . ' supprimé !');

        redirect('admin/listUsers');
    }

    function _check_auth() {
        if (!$this->lib_admin->is_logged_in()) {
            redirect('admin/login');
            exit();
        }
    }

    /**
     * Show info message
     *
     * @param	string
     * @return	void
     */
    function _show_message($message) {
        $this->session->set_flashdata('message', $message);
        redirect('/admin/');
    }

    function listParties() {
        $this->_check_auth();

//load library
        $this->load->library('table');

//make html table for users' list
        $this->table->set_heading('id', 'Titre', 'Descriptif', 'Soirée en ligne', 'Inscriptions en ligne', 'Image Menu', 'Modifier', 'Supprimer');
        $this->table->set_caption('<h3>Soirées</h3>');
        $datas['list'] = $this->table->generate($this->lib_party->get_list_parties_for_table());

//set up view
        $tpl['main'] = $this->load->view('admin/list_parties', $datas, true);
        $tpl['title'] = 'Liste des soirées';
        $tpl['js'][] = js_url('delete_party');
        $this->load->view('admin/template', $tpl);
    }

    function createParty() {
        $this->_check_auth();

//$pic = $this->do_upload($data);

        $this->form_validation->set_rules('name_event', 'name_event', 'trim|required');
        $this->form_validation->set_rules('content', 'content', 'trim|required');



        $data['errors'] = array();

        if ($this->form_validation->run()) {        // validation ok
            if ($this->lib_party->create_party(
                            $this->input->post('name_event'),
                            $this->input->post('content'))) { // success
                redirect('admin/listParties');
            } else {                // fail
                $this->session->set_flashdata('message', 'Création interrompue, réessayez ! <br /> si le problème subsiste contactez l\'administrateur');
                redirect('admin/listParties');
            }
        }

        $tpl['main'] = $this->load->view('admin/new_party_form', $data, true);
        $tpl['title'] = 'Création d\'une soirée';
        $this->load->view('admin/template', $tpl);
    }

    function doUpload() {
        $currentPartyId = (int) $this->uri->segment(3);

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';

        $picturesField = array('picture_menu', 'flyer_front', 'flyer_back');
        $error = array();

        $this->load->library('upload');

        foreach ($picturesField as $pictureField) {
            $this->upload->initialize($config);


            if (!$this->upload->do_upload($pictureField)) {
                $error = array('error' => $this->upload->display_errors());
                break;
            }

            $this->party_model->doUpload($currentPartyId, $pictureField, $this->upload->data());
        }

        if(!empty($error)){            
           $this->session->set_flashdata('message', $error);
           redirect('admin/listParties');
        }else{
            $tpl['main'] = $this->load->view('admin/upload_success', array(), true);
        }
        $this->load->view('admin/template', $tpl);
        
    }

    function updateParty() {

//Check login
        $this->_check_auth();

        $currentPartyId = (int) $this->uri->segment(3);

        $this->form_validation->set_rules('name_event', 'name_event', 'trim|required');
        $this->form_validation->set_rules('content', 'content', 'trim|required');

        $data['errors'] = array();

        if ($this->form_validation->run()) {        // validation ok
            if ($this->lib_party->modify_party($currentPartyId,
                            $this->input->post('name_event'),
                            $this->input->post('content'))) { // success
                $this->session->set_flashdata('message', 'Modifications enregistrées !');
                redirect('admin/listParties');
            } else {                // fail
                $this->session->set_flashdata('message', 'Modifications interrompues, réessayez ! <br /> si le problème subsiste contactez l\'administrateur');
                redirect('admin/listParties');
            }
        }
//get party datas
        $datas['party_infos'] = (array) $this->lib_party->get_party_by_id($currentPartyId);
        $this->load->view('admin/update_party', $datas);
    }

    function deleteParty() {
//Check login
        $this->_check_auth();

        $currentUserId = (int) $this->uri->segment(3);
        $this->party_model->delete_party($currentUserId);

        $this->session->set_flashdata('message', 'Soirée ' . $currentUserId . ' supprimée !');

        redirect('admin/listParties');
    }

}

